﻿using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Web.Mvc;
using Unijovem.Domain;
using Unijovem.UI.Models;

namespace Unijovem.UI.Controllers
{
    public class EventoController : ControllerBase<EventoModel, Evento>
    {
        public ActionResult Visualizar()
        {
            Index();

            foreach (var eventoModel in Models)
            {
                foreach (var evento in ((IEnumerable<Evento>)Dominios).Where(d => d.Id == eventoModel.Id).
                    Where(evento => evento.Pregacaos != null).Where(evento => eventoModel.Pregacoes == null))
                {
                    eventoModel.Pregacoes = new PregacaoModel().CriarViewModel(evento.Pregacaos).ToList();
                }
            }

            return View(Models.OrderBy(e => e.Data));
        }

        public ActionResult MaterialApoio(int id)
        {
            var models =
                new MaterialApoioModel().CriarViewModel(
                    new MaterialApoio().SelectAll<MaterialApoio>().Where(d => d.IdEvento == id));

            return View(models);
        }

        public ActionResult Editar(int id)
        {
            EventoModel model = CarregarEdicao(id);
            PreencherViewBags(model.IdCategoria);

            var models = model.EventoImagems.Select(m => m.Arquivo).ToList();

            foreach (var arquivoModel in models)
                arquivoModel.IdExterno = id;

            Session[string.Concat("ArquivoExterno", model.Id)] = models;

            return View(model);
        }

        [HttpPost]
        public ActionResult Editar(EventoModel model)
        {
            try
            {
                if (!Validar(model))
                    return View();

                SalvarEdicao(model);

                return RedirectToAction("Index");
            }
            catch
            {
                PreencherViewBags(model.IdCategoria);
                return View();
            }
        }

        public void PreencherViewBags(int? idCategoria = null)
        {
            ViewBag.Categorias = new Categoria().SelectAllActive<Categoria>().
                ToSelectList(g => g.Nome, g => g.Id.ToString(), "Categoria", idCategoria.ToString());
        }
    }
}
